package io.lkt.modules.job.task;

import io.lkt.common.utils.*;
import io.lkt.modules.sys.entity.BSysUserWeekScoreEntity;
import io.lkt.modules.sys.entity.SysUserEntity;
import io.lkt.modules.sys.service.BOrderInfoService;
import io.lkt.modules.sys.service.BSysUserWeekScoreService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
@EnableScheduling
@Log4j2
public class SysUserWeekScoreScheduleTask {
    @Autowired
    private BOrderInfoService bOrderInfoService;

    @Autowired
    private BSysUserWeekScoreService bSysUserWeekScoreService;

    /**
     * 每个星期一统计上周(从周一到周日)的系统用户跟进订单得分情况
     */
    @Scheduled(cron = "0 0 0 ? * 2")
    public void addSysUserWeekScore() throws ParseException {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        // 设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        // 获得当前日期是一个星期的第几天
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
        if(dayWeek==1){
            dayWeek = 8;
        }

        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - dayWeek - 7);// 根据日历的规则，给当前日期减去星期几与一个星期第一天的差值
        Date mondayDate = cal.getTime();
        String beginDate = sdf.format(mondayDate) + " 00:00:00";

        cal.add(Calendar.DATE, 4 + cal.getFirstDayOfWeek());
        Date sundayDate = cal.getTime();
        String endDate = sdf.format(sundayDate) + " 23:59:59";

        /*Date firstDayOfLastWeek = DateUtilPlus.getFirstDayOfLastWeek(date);// 上周第一天(周一)
        Date lastDayOfLastWeek = DateUtilPlus.getLastDayOfLastWeek(date);// 上周最后一天(周日)

        String beginDate = DateUtilPlus.formatDate(firstDayOfLastWeek, "yyyy-MM-dd") + " 00:00:00";// 开始时间
        String endDate = DateUtilPlus.formatDate(lastDayOfLastWeek, "yyyy-MM-dd") + " 23:59:59";// 结束时间
        String firstDayOfWeek = DateUtil.getFirstDayOfWeek(date);
        String lastDayOfWeek = DateUtil.getLastDayOfWeek(date) + " 23:59:59";*/
        log.info("[SysUserWeekScoreScheduleTask] 系统用户上周跟进订单积分统计 - from [" + beginDate + "] to [" + endDate + "]");

        Map<String, Object> params = new HashMap<>();
        params.put("beginDate", beginDate);
        params.put("endDate", endDate);

        List<Long> userIdList = new LinkedList<>();
        // 1、获取单位时间内，平台用户的有效跟进订单关于平台用户的跟进次数、跟进积分汇总
        List<SysUserEntity> validFollowOrderSummaryList = bOrderInfoService.getValidFollowOrderSummaryList(params);
        // 2、获取单位时间内，平台用户的有效成交订单号
        List<SysUserEntity> validDealedOrderSummaryList = bOrderInfoService.getValidDealedOrderSummaryList(params);

        if (CollectionUtils.isNotEmpty(validFollowOrderSummaryList)) {
            for (SysUserEntity entity : validFollowOrderSummaryList) {
                userIdList.add(entity.getUserId());
            }
        }

        if (CollectionUtils.isNotEmpty(validDealedOrderSummaryList)) {
            for (SysUserEntity entity : validDealedOrderSummaryList) {
                Long userId = entity.getUserId();
                if (!userIdList.contains(userId)) {
                    userIdList.add(entity.getUserId());
                }
            }
        }

        if (userIdList.size() == 0) {
            return;
        }

        params.put("userIdList", userIdList);
        List<SysUserEntity> list = bOrderInfoService.getSysUserFollowList(params);

        if (CollectionUtils.isNotEmpty(list)) {
            // 3、获取最大期数
            Integer currentMaxPeriod = bSysUserWeekScoreService.getMaxPeriod();
            int maxPeriod = currentMaxPeriod == null ? 1 : currentMaxPeriod.intValue() + 1;

            List<BSysUserWeekScoreEntity> bSysUserWeekScoreEntityList = new ArrayList<>();
            for (SysUserEntity entity : list) {
                BSysUserWeekScoreEntity bSysUserWeekScoreEntity = new BSysUserWeekScoreEntity();// 实体：平台用户周得分实体
                Long userId = entity.getUserId();
                // 插入跟进次数和跟进积分
                if (CollectionUtils.isNotEmpty(validFollowOrderSummaryList)) {
                    for (SysUserEntity followEntity : validFollowOrderSummaryList) {
                        Long followUserId = followEntity.getUserId();
                        if (userId.equals(followUserId)) {
                            entity.setFollowCount(followEntity.getFollowCount());

                            Integer followScore = followEntity.getFollowScore();
//                            entity.setFollowScore(followScore);
                            entity.setTotalScore(Optional.ofNullable(followScore).orElse(0));
                            break;
                        }
                    }
                }

                // 插入成交订单数和成交订单积分
                if (CollectionUtils.isNotEmpty(validDealedOrderSummaryList)) {
                    for (SysUserEntity dealedEntity : validDealedOrderSummaryList) {
                        Long dealedUserId = dealedEntity.getUserId();
                        if (userId.equals(dealedUserId)) {
                            entity.setDealedCount(dealedEntity.getDealedCount());

                            Integer dealedScore = dealedEntity.getDealedScore();
                            entity.setDealedScore(dealedScore);
                            Integer totalScore = Optional.ofNullable(entity.getTotalScore()).orElse(0);
                            entity.setTotalScore(totalScore + Optional.ofNullable(dealedScore).orElse(0));
                            break;
                        }
                    }
                }
                bSysUserWeekScoreEntity.setUserId(userId);// 用户ID
                bSysUserWeekScoreEntity.setFollowCount(Optional.ofNullable(entity.getFollowCount()).orElse(0));// 跟进次数
                bSysUserWeekScoreEntity.setDealedCount(Optional.ofNullable(entity.getDealedCount()).orElse(0));// 成交订单数量
                bSysUserWeekScoreEntity.setDealedScore(Optional.ofNullable(entity.getDealedScore()).orElse(0));// 成交订单得分(成交订单得分 = 成交订单数量 * 5)
                bSysUserWeekScoreEntity.setTotalScore(Optional.ofNullable(entity.getTotalScore()).orElse(0));// 总得分
                bSysUserWeekScoreEntity.setPeriod(maxPeriod);// 期数
                bSysUserWeekScoreEntity.setBeginTime(DateUtilPlus.parseDate(beginDate, "yyyy-MM-dd HH:mm:ss"));// 开始时间
                bSysUserWeekScoreEntity.setEndTime(DateUtilPlus.parseDate(endDate, "yyyy-MM-dd HH:mm:ss"));// 结束时间
                bSysUserWeekScoreEntity.setCreateTime(new Date());// 创建时间
                bSysUserWeekScoreEntityList.add(bSysUserWeekScoreEntity);
            }

            // 4、批量插入上周的数据
            bSysUserWeekScoreService.saveBatch(bSysUserWeekScoreEntityList);
        }
    }
}
